package com.teach.javafxclient.util;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.controller.base.LoginController;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.ProgressIndicator;
import kong.unirest.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;

/**
 * @author Liang Jianlin
 * @date 2024-05-16 15:04
 */

public class HttpUtil {
    public static HttpRequest<GetRequest> get(String url){
        // 获取文件路径
        String desktopPath = System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop";
        String filePath = desktopPath + System.getProperty("file.separator") + "smsFile" + System.getProperty("file.separator") + "timestamp.txt";

        // 读取时间戳
        long savedTimestamp = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line = reader.readLine();
            if (line != null) {
                savedTimestamp = Long.parseLong(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("读取文件时出错：" + e.getMessage());
        }

        // 如果没有读取到时间戳，则退出
        if (savedTimestamp == 0) {
            System.out.println("文件中没有有效的时间戳。");
        }

        // 获取当前时间
        Instant now = Instant.now();

        // 计算时间差
        Duration duration = Duration.between(Instant.ofEpochMilli(savedTimestamp), now);

        // 判断是否超过两个半小时（2.5小时 * 60分钟/小时 * 60秒/分钟 * 1000毫秒/秒）
        long twoHoursAndHalfMillis = 2L * 60 * 60 * 1000 + 30 * 60 * 1000;
        if (duration.toMillis() > twoHoursAndHalfMillis) {
            System.out.println("时间戳与现在时间相差超过两个半小时。");
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/login-view.fxml"));
            Parent Root = null;
            try {
                Root = fxmlLoader.load();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            LoginController LC = fxmlLoader.getController();
            LC.loginButton.setOnAction(e->LC.reLoginButtonClick());
            DialogUtil.show(600,450,"登录过期",Root);
            throw new RuntimeException("token 过期");
        } else {
            System.out.println("时间戳与现在时间没有超过两个半小时。");
        }
        return Unirest.get(url)
                .header("Authorization", "Bearer " + Globalvar.userToken);
    }
    public static HttpRequestWithBody post(String url){
        // 获取文件路径
        String desktopPath = System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop";
        String filePath = desktopPath + System.getProperty("file.separator") + "smsFile" + System.getProperty("file.separator") + "timestamp.txt";

        // 读取时间戳
        long savedTimestamp = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line = reader.readLine();
            if (line != null) {
                savedTimestamp = Long.parseLong(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("读取文件时出错：" + e.getMessage());
        }

        // 如果没有读取到时间戳，则退出
        if (savedTimestamp == 0) {
            System.out.println("文件中没有有效的时间戳。");
        }

        // 获取当前时间
        Instant now = Instant.now();

        // 计算时间差
        Duration duration = Duration.between(Instant.ofEpochMilli(savedTimestamp), now);

        // 判断是否超过两个半小时（2.5小时 * 60分钟/小时 * 60秒/分钟 * 1000毫秒/秒）
        long twoHoursAndHalfMillis = 2L * 60 * 60 * 1000 + 30 * 60 * 1000;
        if (duration.toMillis() > twoHoursAndHalfMillis) {
            System.out.println("时间戳与现在时间相差超过两个半小时。");
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/login-view.fxml"));
            Parent Root = null;
            try {
                Root = fxmlLoader.load();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            LoginController LC = fxmlLoader.getController();
            LC.loginButton.setOnAction(e->LC.reLoginButtonClick());
            DialogUtil.show(600,450,"登录过期",Root);
            throw new RuntimeException("token 过期");
        } else {
            System.out.println("时间戳与现在时间没有超过两个半小时。");
        }
        return Unirest.post(url)
                .header("Authorization", "Bearer " + Globalvar.userToken);
    }
    public static HttpRequestWithBody put(String url){
        // 获取文件路径
        String desktopPath = System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop";
        String filePath = desktopPath + System.getProperty("file.separator") + "smsFile" + System.getProperty("file.separator") + "timestamp.txt";

        // 读取时间戳
        long savedTimestamp = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line = reader.readLine();
            if (line != null) {
                savedTimestamp = Long.parseLong(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("读取文件时出错：" + e.getMessage());
        }

        // 如果没有读取到时间戳，则退出
        if (savedTimestamp == 0) {
            System.out.println("文件中没有有效的时间戳。");
        }

        // 获取当前时间
        Instant now = Instant.now();

        // 计算时间差
        Duration duration = Duration.between(Instant.ofEpochMilli(savedTimestamp), now);

        // 判断是否超过两个半小时（2.5小时 * 60分钟/小时 * 60秒/分钟 * 1000毫秒/秒）
        long twoHoursAndHalfMillis = 2L * 60 * 60 * 1000 + 30 * 60 * 1000;
        if (duration.toMillis() > twoHoursAndHalfMillis) {
            System.out.println("时间戳与现在时间相差超过两个半小时。");
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/login-view.fxml"));
            Parent Root = null;
            try {
                Root = fxmlLoader.load();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            LoginController LC = fxmlLoader.getController();
            LC.loginButton.setOnAction(e->LC.reLoginButtonClick());
            DialogUtil.show(600,450,"登录过期",Root);
            throw new RuntimeException("token 过期");
        } else {
            System.out.println("时间戳与现在时间没有超过两个半小时。");
        }
        return Unirest.put(url)
                .header("Authorization", "Bearer " + Globalvar.userToken);
    }
    public static HttpRequestWithBody delete(String url){
        // 获取文件路径
        String desktopPath = System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop";
        String filePath = desktopPath + System.getProperty("file.separator") + "smsFile" + System.getProperty("file.separator") + "timestamp.txt";

        // 读取时间戳
        long savedTimestamp = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line = reader.readLine();
            if (line != null) {
                savedTimestamp = Long.parseLong(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("读取文件时出错：" + e.getMessage());
        }

        // 如果没有读取到时间戳，则退出
        if (savedTimestamp == 0) {
            System.out.println("文件中没有有效的时间戳。");
        }

        // 获取当前时间
        Instant now = Instant.now();

        // 计算时间差
        Duration duration = Duration.between(Instant.ofEpochMilli(savedTimestamp), now);

        // 判断是否超过两个半小时（2.5小时 * 60分钟/小时 * 60秒/分钟 * 1000毫秒/秒）
        long twoHoursAndHalfMillis = 2L * 60 * 60 * 1000 + 30 * 60 * 1000;
        if (duration.toMillis() > twoHoursAndHalfMillis) {
            System.out.println("时间戳与现在时间相差超过两个半小时。");
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/login-view.fxml"));
            Parent Root = null;
            try {
                Root = fxmlLoader.load();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            LoginController LC = fxmlLoader.getController();
            LC.loginButton.setOnAction(e->LC.reLoginButtonClick());
            DialogUtil.show(600,450,"登录过期",Root);
            throw new RuntimeException("token 过期");
        } else {
            System.out.println("时间戳与现在时间没有超过两个半小时。");
        }
        return Unirest.delete(url)
                .header("Authorization", "Bearer " + Globalvar.userToken);
    }
}
